const R = require('@/models/Response')
const { SystemOption } = require('@/models/model')
const { ERROR_SYSTEM_CODE } = require('@/constants/errorCode')
const { ERROR_MESSAGE } = require('@/constants/system')
const { setConfig } = require('@/config/system')

/**
 * 修改系统配置的接口
 * @param {*} ctx
 * @returns
 */
module.exports.setSystemOpt = async (ctx) => {
  try {
    Object.entries(ctx.request.body).forEach(async ([key, value]) => {
      try {
        await SystemOption.update(
          {
            value: '' + value
          },
          {
            where: {
              key
            }
          }
        )
        // 成功更改一个配置项，同步修改应用的配置
        setConfig(key, '' + value)
      } catch (e) {
        e.key = key
        throw e
      }
    })
    ctx.body = R.success()
  } catch (e) {
    ctx.body = R.error({
      code: ERROR_SYSTEM_CODE.SYSTEM_OPTION_ERROR.code,
      message: `设置${ERROR_MESSAGE[e.key]}失败`
    })
  }
}

/**
 * 列表查询系统配置的接口
 * @param {*} ctx
 * @returns
 */
module.exports.listSystemOpt = async (ctx) => {
  const opts = await SystemOption.findAll()
  let obj = {}
  for (let i = 0; i < opts.length; i++) {
    let item = opts[i]
    obj[item.key] = item.value
    //
  }
  ctx.body = R.success(obj)
}

/**
 * 未登录用户查询系统配置的接口
 * @param {*} ctx
 * @returns
 */
module.exports.unLoginlistSystemOpt = async (ctx) => {
  const opts = await SystemOption.findAll()

  const validateKey = [
    'dataFormat',
    'loginValidateCode',
    'msgValidateCode',
    'companyName',
    'companySubName'
  ]
  let obj = {}
  for (let i = 0; i < opts.length; i++) {
    let item = opts[i]
    if (validateKey.includes(item.key)) {
      obj[item.key] = item.value
    }
  }
  ctx.body = R.success(obj)
}
